package com.suntront.module_login.login

import android.content.Context
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.rxLifeScope
import com.alibaba.android.arouter.launcher.ARouter
import com.mtjsoft.www.kotlinmvputils.base.BaseViewModel
import com.mtjsoft.www.kotlinmvputils.constants.RouterConstants
import com.mtjsoft.www.kotlinmvputils.event.SingleLiveEvent
import com.mtjsoft.www.kotlinmvputils.rxhttp.RxUrl
import com.mtjsoft.www.kotlinmvputils.rxhttp.error.code
import com.mtjsoft.www.kotlinmvputils.rxhttp.error.msg
import com.mtjsoft.www.kotlinmvputils.utils.AndAppUtils
import com.mtjsoft.www.kotlinmvputils.utils.MD5
import com.suntront.module_login.entity.LoginResponse
import com.tencent.mmkv.MMKV
import rxhttp.await
import rxhttp.wrapper.param.RxHttp

/**
 * @author mtj
 * @Package com.suntront.module_login.login
 * @date 2020-05-25 15:40:04
 */

class LoginViewModel : BaseViewModel() {

    private val nameSingleLiveEvent: SingleLiveEvent<String> = SingleLiveEvent()

    private val pswSingleLiveEvent: SingleLiveEvent<String> = SingleLiveEvent()

    private val version: SingleLiveEvent<String> = SingleLiveEvent()


    fun setName(view: EditText) {
        nameSingleLiveEvent.value = MMKV.defaultMMKV().decodeString("name", "")
        view.setText(nameSingleLiveEvent.value)
        view.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable) {
                nameSingleLiveEvent.postValue(s.toString())
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
    }

    fun setPsw(view: EditText) {
        pswSingleLiveEvent.value = MMKV.defaultMMKV().decodeString("pwd", "")
        view.setText(pswSingleLiveEvent.value)
        view.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable) {
                pswSingleLiveEvent.postValue(s.toString())
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
    }

    fun setVersion(view: TextView, context: Context) {
        version.value = AndAppUtils.getVerName(context)
        view.text = "V${version.value.toString()}"
    }

    fun login() {
        if (TextUtils.isEmpty(nameSingleLiveEvent.value)) {
            showToastUI("请输入账号")
            return
        }
        if (TextUtils.isEmpty(pswSingleLiveEvent.value)) {
            showToastUI("请输入密码")
            return
        }
        rxLifeScope.launch({    //通过launch方法开启一个协程
            val loginResponse = RxHttp.postJson(RxUrl.LOGIN)
                .add("UserAccount", nameSingleLiveEvent.value.toString())
                .add(
                    "UserPwd",
                    MD5.getMessageDigest(pswSingleLiveEvent.value.toString().toByteArray())
                )
                .add("ClientId", MMKV.defaultMMKV().decodeString("ClientId", "123456"))
                .await<LoginResponse>()
            if (loginResponse.isResult) {
                MMKV.defaultMMKV().encode("name", nameSingleLiveEvent.value.toString())
                MMKV.defaultMMKV().encode("AdminID", loginResponse.userId)
                MMKV.defaultMMKV().encode("AdminName", loginResponse.realName)
                MMKV.defaultMMKV().encode("pwd", pswSingleLiveEvent.value.toString())
                MMKV.defaultMMKV().encode("allowoffline", 1)
                // 登录成功，跳主页
                ARouter.getInstance().build(RouterConstants.MAIN_ACTIVITY).navigation()
                finishUI()
            } else {
                showToastUI(loginResponse.msg)
            }
        }, {
            //异常回调，这里的it为Throwable类型
            val code = it.code
            val msg = it.msg
            showToastUI(msg)
        }, {
            showLoadingUI("正在登录...", false)
        }, {
            hideLoadingUI()
        })
    }
}